package wht.jly.forum.utils.validatecode.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;
import wht.jly.forum.utils.validatecode.image.ImageValidateCode;
import wht.jly.forum.utils.validatecode.image.ImageValidateCodeGenerator;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 图形验证码控制器
 *
 * @author lanyangji
 * @date 2019/3/2 19:17
 */
@RestController
public class ImageValidateCodeController {

    public static final String SESSION_KEY_IMAGE_VALIDATE_CODE = "image_validate_code";

    @Autowired
    private ImageValidateCodeGenerator imageValidateCodeGenerator;

    @GetMapping("/code/image")
    public void createImageValidateCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获得 ImageValidateCode
        ImageValidateCode imageValidateCode = imageValidateCodeGenerator.generate(new ServletWebRequest(request));
        // 存到 session中
        request.getSession().setAttribute(SESSION_KEY_IMAGE_VALIDATE_CODE, imageValidateCode);
        // 写出去
        ImageIO.write(imageValidateCode.getImage(), "JPEG", response.getOutputStream());
    }

}
